// k8sclient.go
package common

import (
	"log"
	"os"

	"k8s.io/client-go/kubernetes"
	"k8s.io/client-go/rest"
	"k8s.io/client-go/tools/clientcmd"
)

func ClientSet(clusterid string) *kubernetes.Clientset {
	var kubeconfigPath string
	switch clusterid {
	case "ali-cluster1":
		kubeconfigPath = "./ali-cluster1.txt"
	case "ali-cluster2":
		kubeconfigPath = "./ali-cluster2.txt"
	default:
		kubeconfigPath = "./kubeconfig.txt"
	}
	config, err := clientcmd.BuildConfigFromFlags("", kubeconfigPath)
	if err != nil {
		panic(err.Error())
	}
	config.QPS = 10
	config.Burst = 100

	if clusterid == "aws-cluster1" { //针对aws的k8s集群需要读取token来进行验证
		bearerToken, err := GetBearerTokenByClusterId(kubeconfigPath)
		if err != nil {
			//panic(err.Error())
			log.Printf("[ERROR] GetBearerTokenByClusterId err:%s\n", err)
		}
		//log.Println(bearerToken)
		if bearerToken != "" && bearerToken != "null" {
			config.BearerToken = bearerToken
		}
	}

	// create the clientset
	clientset, err := kubernetes.NewForConfig(config)
	if err != nil {
		panic(err.Error())
	}

	bearerToken, err2 := GetBearerTokenByClusterId(clusterid)
	if err2 != nil {
		//panic(err.Error())
		log.Printf("[ERROR] GetBearerTokenByClusterId err:%s\n", err2)
	}
	//log.Println(bearerToken)
	if bearerToken != "" && bearerToken != "null" {
		config.BearerToken = bearerToken
	}

	return clientset
}

func ClientSetConfig(clusterid string) (*kubernetes.Clientset, *rest.Config) {
	var kubeconfigPath string
	switch clusterid {
	case "ali-cluster1":
		kubeconfigPath = "./ali-cluster1.txt"
	case "ali-cluster2":
		kubeconfigPath = "./ali-cluster2.txt"
	default:
		kubeconfigPath = "./kubeconfig.txt"
	}
	config, err := clientcmd.BuildConfigFromFlags("", kubeconfigPath)
	if err != nil {
		panic(err.Error())
	}
	config.QPS = 10
	config.Burst = 100
	// create the clientset
	clientset, err := kubernetes.NewForConfig(config)
	if err != nil {
		panic(err.Error())
	}
	return clientset, config
}

func GetBearerTokenByClusterId(tokenFilePath string) (string, error) {
	content, err := os.ReadFile(tokenFilePath)
	if err != nil {
		return "", err
	}
	return string(content), nil
}
